﻿using System;
using System.IO;
using System.Configuration;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace AzureForm
{
    public partial class MainQueueExplorer : Form
    {
        public MainQueueExplorer()
        {
            InitializeComponent();
        }

        private void addNewConnectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmNewConnection newConn = new frmNewConnection();            
            newConn.MyMain = this;
            newConn.ShowDialog(this);
        }

        public void makenewmenuitem(string name, string connstr)
        {           
            try
            {
                TreeNode LVI = new TreeNode();
                LVI.Name = string.Format("connectionToolStripMenuItem{0}", connstr);
                LVI.Text = name;
                LVI.Tag = connstr;
                LVI.ImageIndex = 1;
                LVI.SelectedImageIndex = 1;
                LVI.ToolTipText = "Azure Connection: " + name;

                AzureStorageList.Nodes[0].Nodes.Add(LVI);
                refreshQeueus(LVI);
                AzureStorageList.ExpandAll();
            }
            catch
            {
                MessageBox.Show("Connection Is not working", "Error connecting to storage");
            }
        }



        private void removeConnectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RefreshConnections();
        }

        private void AzureMainList_MouseDown(object sender, MouseEventArgs e)
        {
            TreeViewHitTestInfo hitTestInfo = AzureStorageList.HitTest(e.X, e.Y);
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                AzureStorageList.ContextMenuStrip = null;
                TreeNode LVI = hitTestInfo.Node;
                if (LVI != null && LVI.Tag!=null)
                {
                    AzureStorageList.SelectedNode = LVI;
                    switch (LVI.Tag.ToString())
                    {
                        case "Main":
//                            AzureStorageList.ContextMenuStrip.Show(new Point(e.X, e.Y));
                            AzureStorageList.ContextMenuStrip = contextMenu_Connections;
                            break;
                        case "Queue":
                            AzureStorageList.ContextMenuStrip = contextMenu_Queue;
                            break;
                        default:
                            if (LVI.ToolTipText.StartsWith("Azure Connection"))
                            {
                                AzureStorageList.ContextMenuStrip = contextMenu_StorageConnection;
                            }
                            break;
                    }
                }


            }

        }

        private void RefreshConnections()
        {
            Configuration cfg = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
            
            if (!cfg.HasFile)
            {
                StreamWriter swr = File.CreateText(string.Format("{0}",cfg.FilePath));
                swr.Close();
            }


            int t = 0;
            AzureStorageList.Nodes[0].Nodes.Clear();
            foreach (ConnectionStringSettings css in cfg.ConnectionStrings.ConnectionStrings)
            {
                TreeNode LVI = new TreeNode();
                LVI.Name = string.Format("connectionToolStripMenuItem{0}", t++);
                LVI.Text = css.Name;
                LVI.Tag = css.ConnectionString;
                LVI.ImageIndex = 1;
                LVI.SelectedImageIndex = 1;
                LVI.ToolTipText = "Azure Connection: " + css.Name;

                if (css.Name != "LocalSqlServer")
                {
                    refreshQeueus(LVI);
                    AzureStorageList.Nodes[0].Nodes.Add(LVI);
                }
                else
                {

                }
            }
            AzureStorageList.ExpandAll();
        }


        private void MainQueueExplorer_Load(object sender, EventArgs e)
        {
            RefreshConnections();
        }

        private void yesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode MyNode = AzureStorageList.SelectedNode;
            if (MyNode.ToolTipText.StartsWith("Azure Connection"))
            {
                Configuration cfg = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
                int t = 0, sitem = -1;

                foreach (ConnectionStringSettings css in cfg.ConnectionStrings.ConnectionStrings)
                {
                    if (css.Name == MyNode.Text)
                    {
                        sitem = t;
                        break;
                    }
                    t++;
                }
                if (sitem > 0)
                {
                    cfg.ConnectionStrings.ConnectionStrings.RemoveAt(sitem);
                    AzureStorageList.Nodes.Remove(MyNode);
                    cfg.Save(ConfigurationSaveMode.Full);
                }
            }
        }

        private void refreshQeueus(TreeNode TN1)
        {
            CloudStorageAccount account;
            string conn = TN1.Tag.ToString();
            account = CloudStorageAccount.Parse(conn);

            Microsoft.WindowsAzure.StorageClient.CloudQueueClient ccq = account.CreateCloudQueueClient();// new CloudQueueClient(account.QueueEndpoint, account.Credentials);
            
            int t=0;
            TN1.Nodes.Clear();
            foreach (CloudQueue cq in ccq.ListQueues())
            {
                TreeNode LVI = new TreeNode();
                LVI.Name = string.Format("Queues{0}", t++);
                LVI.Text = cq.Name;
                LVI.Tag = "Queue";
                LVI.ImageIndex = 2;
                LVI.SelectedImageIndex = 2;

                TN1.Nodes.Add(LVI);
                t++;
            }
            TN1.ExpandAll();
        }

        private void addQueueToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddQueue frmAddQueue = new AddQueue();

            if (frmAddQueue.ShowDialog(this) == DialogResult.OK)
            {
                TreeNode MyNode = AzureStorageList.SelectedNode;
                CloudStorageAccount account;
                string conn = MyNode.Tag.ToString();
                string QueueName = frmAddQueue.QueueName.ToLower();

                account = CloudStorageAccount.Parse(conn);

                Microsoft.WindowsAzure.StorageClient.CloudQueueClient ccq = account.CreateCloudQueueClient();// new CloudQueueClient(account.QueueEndpoint, account.Credentials);
                Microsoft.WindowsAzure.StorageClient.CloudQueue cq = ccq.GetQueueReference(QueueName);
                try
                {
                    cq.CreateIfNotExist();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Creation of Queue Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                refreshQeueus(MyNode);
            }
        }

        private void refreshQueuesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode MyNode = AzureStorageList.SelectedNode;
            refreshQeueus(MyNode);
        }

        private void yesToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            TreeNode MyNode = AzureStorageList.SelectedNode;
            CloudStorageAccount account;
            string conn = MyNode.Parent.Tag.ToString();
            
            account = CloudStorageAccount.Parse(conn);

            Microsoft.WindowsAzure.StorageClient.CloudQueueClient ccq = account.CreateCloudQueueClient();// new CloudQueueClient(account.QueueEndpoint, account.Credentials);
            Microsoft.WindowsAzure.StorageClient.CloudQueue cq = ccq.GetQueueReference(MyNode.Text);
            try
            {
                cq.Delete();
                MyNode.Remove();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Delete of Queue Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void lstQueueItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstQueueItems.SelectedItem != null)
            {
                string message = lstQueueItems.SelectedItem.ToString();
                int p1 = message.IndexOf("_");
                if (p1 > 0)
                {
                    string messageid = message.Substring(0, p1);

                    string Connection = lblConnection.Text;
                    string QueueName = lblSendQueueName.Text;
                    CloudStorageAccount account;

                    //string ConfigName = QueueName.Substring(0, QueueName.IndexOf("/"));

                    //QueueName = QueueName.Substring(QueueName.IndexOf("/") + 1);

                    account = CloudStorageAccount.Parse(Connection);

                    Microsoft.WindowsAzure.StorageClient.CloudQueueClient ccq = account.CreateCloudQueueClient();
                    Microsoft.WindowsAzure.StorageClient.CloudQueue cq = ccq.GetQueueReference(QueueName);

                    CloudQueueMessage cMes = new CloudQueueMessage("");
                    foreach (CloudQueueMessage cMess in cq.PeekMessages(25))
                    {
                        if (cMess.Id == messageid)
                        {
                            cMes = cMess;
                            break;
                        }
                    }

                    txtMessageID.Text = cMes.Id;
                    txtInserted.Text = cMes.InsertionTime.ToString();
                    txtExpired.Text = cMes.ExpirationTime.ToString();
                    txtPopReceipt.Text = string.Empty;
                    txtDeQueueCount.Text = cMes.DequeueCount.ToString();
                    txtMessage.Text = cMes.AsString;

                    tabPage1.Show();
                    tabControl1.SelectedIndex = 0;
                    
                }
            }
        }

        private void btnGetNextMessageOffQueue_Click(object sender, EventArgs e)
        {
            btnGetNextMessageOffQueue.Enabled=false;
            try
            {                
                string Connection = lblConnection.Text;
                string QueueName = lblSendQueueName.Text;
                CloudStorageAccount account;

                //string ConfigName = QueueName.Substring(0, QueueName.IndexOf("/"));

                //QueueName = QueueName.Substring(QueueName.IndexOf("/") + 1);

                account = CloudStorageAccount.Parse(Connection);

                Microsoft.WindowsAzure.StorageClient.CloudQueueClient ccq = account.CreateCloudQueueClient();
                Microsoft.WindowsAzure.StorageClient.CloudQueue cq = ccq.GetQueueReference(QueueName);

                TimeSpan tsDelay = new TimeSpan(Convert.ToInt16(numericUpDown_Hour.Value), Convert.ToInt16(numericUpDown_Minute.Value), 0);

                CloudQueueMessage cMes = cq.GetMessage(tsDelay);

                txtMessageID.Text = cMes.Id;
                txtInserted.Text = cMes.InsertionTime.ToString();
                txtExpired.Text = cMes.ExpirationTime.ToString();
                txtPopReceipt.Text = cMes.PopReceipt;
                txtDeQueueCount.Text = cMes.DequeueCount.ToString();
                txtMessage.Text = cMes.AsString;

                RefreshMessages(Connection, QueueName);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Failed to Get Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            btnGetNextMessageOffQueue.Enabled=true;
        }

        private void AzureStorageList_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode MyNode = AzureStorageList.SelectedNode;
            if (MyNode != null && MyNode.Tag != null)
            {
                switch (MyNode.Tag.ToString())
                {
                    case "Queue":
                        string Connection = MyNode.Parent.Tag.ToString();
                        string QueueName = MyNode.Text;
                        lblConnection.Text = Connection;
                        lblQueueName.Text = string.Format("{0}\\{1}", MyNode.Parent.Text, MyNode.Text);
                        lblSendQueueName.Text = string.Format("{1}", MyNode.Parent.Text, MyNode.Text);

                        RefreshMessages(Connection, QueueName);
                        break;
                }
            }
        }

        private void RefreshMessages(string Connection,string QueueName)
        {
            CloudStorageAccount account;

            account = CloudStorageAccount.Parse(Connection);

            Microsoft.WindowsAzure.StorageClient.CloudQueueClient ccq = account.CreateCloudQueueClient();
            Microsoft.WindowsAzure.StorageClient.CloudQueue cq = ccq.GetQueueReference(QueueName);

            lstQueueItems.Items.Clear();
            foreach (CloudQueueMessage CCM in cq.PeekMessages(25))
            {
                string MyMessage = CCM.AsString;
                if (MyMessage.Length > 25)
                {
                    MyMessage = MyMessage.Substring(0, 25);
                }
                lstQueueItems.Items.Add(string.Format("{0}_{1}_[{2}]", CCM.Id, CCM.InsertionTime, MyMessage));
            }

        }


        private void btnSendMessage_Click(object sender, EventArgs e)
        {
            btnSendMessage.Enabled=false;
            try
            {
                string Connection = lblConnection.Text;
                string QueueName = lblSendQueueName.Text;
                CloudStorageAccount account;

                account = CloudStorageAccount.Parse(Connection);

                Microsoft.WindowsAzure.StorageClient.CloudQueueClient ccq = account.CreateCloudQueueClient();
                Microsoft.WindowsAzure.StorageClient.CloudQueue cq = ccq.GetQueueReference(QueueName);

                CloudQueueMessage cmess = new CloudQueueMessage(txtNewQueueMessage.Text);

                TimeSpan tLive = new TimeSpan(Convert.ToInt16(numericUpDown_TimeToLiveHour.Value), Convert.ToInt16(numericUpDown_TimeToLiveMinute.Value), 0);

                cq.AddMessage(cmess, tLive);

                RefreshMessages(Connection, QueueName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Failed to Send Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            btnSendMessage.Enabled=true;
        }

        private void btnConfirmReceipt_Click_1(object sender, EventArgs e)
        {
            btnConfirmReceipt.Enabled=false;
            try
            {
                string Connection = lblConnection.Text;
                string QueueName = lblSendQueueName.Text;
                CloudStorageAccount account;

                account = CloudStorageAccount.Parse(Connection);

                Microsoft.WindowsAzure.StorageClient.CloudQueueClient ccq = account.CreateCloudQueueClient();
                Microsoft.WindowsAzure.StorageClient.CloudQueue cq = ccq.GetQueueReference(QueueName);

                cq.DeleteMessage(txtMessageID.Text, txtPopReceipt.Text);

                txtMessageID.Text = string.Empty;
                txtInserted.Text = string.Empty;
                txtExpired.Text = string.Empty;
                txtPopReceipt.Text = string.Empty;
                txtDeQueueCount.Text = string.Empty;
                txtMessage.Text = string.Empty;
                
                RefreshMessages(Connection, QueueName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Failed to Delete Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            btnConfirmReceipt.Enabled=true;
        }

        private void refreshQueueToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            string Connection = lblConnection.Text;
            string QueueName = lblSendQueueName.Text;

            RefreshMessages(Connection, QueueName);
        }
    }
}
